<?php

namespace app\adminapi\controller\merchant;

use app\adminapi\controller\BaseAdminController;
use app\adminapi\http\middleware\MerchantMiddleware;
use app\adminapi\lists\CardLists;
use app\adminapi\lists\WithdrawOrderLists;
use app\common\model\CommissionLog;
use app\common\model\Merchant;
use app\common\model\WithdrawOrder;

class WithdrawController extends BaseAdminController
{
    protected $middleware = [
        MerchantMiddleware::class,
    ];


    public function lists()
    {
        return $this->dataLists(new WithdrawOrderLists(['merchant_id' => $this->request->merhchant_id]));
    }


    public function blance()
    {


    }



    public function apply()
    {
        $amount = $this->request->param('amount', 0);
        $merchant_id = $this->request->merhchant_id;
        /**
         * @var Merchant $merchant
         */
        $merchant = Merchant::findOrFail($merchant_id);
        if ($merchant->commission < $amount) {
            return $this->fail('余额不足');
        }

        try {
            /**
             * @var WithdrawOrder $withdrawOrder
             */
            $withdrawOrder = new WithdrawOrder();
            $withdrawOrder->merchant_id = $merchant_id;
            $withdrawOrder->amount = $amount;
            $withdrawOrder->sn = generate_sn(WithdrawOrder::class, 'sn');
            $withdrawOrder->create_time = time();
            $withdrawOrder->account = $this->request->param('account');
            $withdrawOrder->way = $this->request->param('way');
            $withdrawOrder->save();

            CommissionLog::log($merchant, -$amount, '提现申请'.$withdrawOrder->sn);
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }


        return $this->success('申请成功');
    }


}